package com.sp2.dev.jdbc.exception;

import com.sp2.dev.constant.JDBCPoperties;

import java.sql.*;

/**
 * Created by IntelliJ IDEA.
 * User: zhimingli
 * Date: 14-1-23
 * Time: 下午12:13
 * To change this template use File | Settings | File Templates.
 */
public class DBConnection {
    private Connection conn = null;
    private PreparedStatement pstmt = null;
    private ResultSet rs = null;

    /**
     * 创建链接
     *
     * @return
     */
    public Connection getConnection() {

        String jdbc_driver = "com.mysql.jdbc.Driver";
        String jdbc_url = "jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8";
        String jdbc_user = "root";
        String jdbc_pass = "root";

        try {

            if (JDBCPoperties.jdbc_driver == null) {
                JDBCPoperties.jdbc_driver = jdbc_driver;
                JDBCPoperties.jdbc_url = jdbc_url;
                JDBCPoperties.jdbc_user = jdbc_user;
                JDBCPoperties.jdbc_pass = jdbc_pass;
            }

            Class.forName(JDBCPoperties.jdbc_driver);
            //创建数据库连接
            conn = DriverManager.getConnection(JDBCPoperties.jdbc_url, JDBCPoperties.jdbc_user, JDBCPoperties.jdbc_pass);
            //创建Statement对象
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭链接
     */
    public void closeConn() {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //method3: 专门用于发送增删改语句的方法
    public int execOther(PreparedStatement pstmt) {
        try {
            //1、使用Statement对象发送SQL语句
            int affectedRows = pstmt.executeUpdate();
            //2、返回结果
            return affectedRows;
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

    //method4: 专门用于发送查询语句
    public ResultSet execQuery(PreparedStatement pstmt) {
        try {
            //1、使用Statement对象发送SQL语句
            rs = pstmt.executeQuery();
            //2、返回结果
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
